package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.yxt.common.sort.MapComparator;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.ListTableAdapter;
import com.yxt.common.ui.TextItemOnClickListener;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Listener;

public class RainStationListActivity extends Activity {
	private static final int MENU_SEARCH = Menu.FIRST+1;
	private static final int MENU_ONE = Menu.FIRST+2;
	private static final int MENU_THREE = Menu.FIRST + 3;
	private static final int MENU_SIX = Menu.FIRST + 4;
	private static final int MENU_DAY = Menu.FIRST + 5;
	
	private Map<String,String> header = new HashMap<String,String>();
	private List<Map<String, String>> list = new ArrayList<Map<String, String>>();
	private MapComparator comparator = new MapComparator();
	private String[] from = { "name", "value", "addr"};
	private int[] to = {R.id.lbl1,R.id.lbl2,R.id.lbl3};	
	private String[] keys = {"code"};
	private String shiduan;
	private String qiangdu;
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.rain_list);   //软件activity的布局
		ActivityStackControlUtil.add(this);
		
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		TextView lblTitle2 = (TextView)findViewById(R.id.lblTitle2);
		lblTitle2.setOnClickListener(new OnClickListener(){			
			public void onClick(View arg0) {
				fillListView("value");
			}
		});
		initComponent();
	}

	private void downloadRainStation() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new RainStationHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}
	}

	private InputStream getInputStream() throws IOException{
		String server = CommConstant.Sever.RAIN_SERVER;
		if (shiduan == null) {
			Intent intent = getIntent();
			shiduan = intent.getStringExtra("shiduan");
			qiangdu = intent.getStringExtra("qiangdu");				
		}
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"rainlocation.xml");
		} else {
			URL url = new URL(server + "rain/StaList.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&shiduan="+shiduan+"&qiangdu="+qiangdu+"&orderby=");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
	
	private class RainStationHandler extends DefaultHandler {
		public void startDocument() throws SAXException {
			header.clear();
			list.clear();
		}
		
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("stacount".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					header.put(attrs.getLocalName(i), attrs.getValue(i));
				}
			} else if ("sta".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				list.add(data);
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}		
	}
	
	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					Intent intent = getIntent();
					TextView lblTitle = (TextView)findViewById(R.id.lblTitle);
					lblTitle.setText(intent.getStringExtra("name")+"(" + header.get("value")+"){"+CommConstant.Rain.CALC_TIME+"}");
					fillListView("");
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadRainStation();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	private void fillListView(String key) {
		if (!"".equals(key)) {
			comparator.setKey(key);
			Collections.sort(list, comparator);
		}

		List<Listener> items = new ArrayList<Listener>();
		for (int i = 0; i < from.length; i++) {
			Listener listener = new Listener(to[i],new TextItemOnClickListener(this, RainStationDetailActivity.class));
			items.add(listener);
		}
		items.add(new Listener(R.id.imgdetail,new TextItemOnClickListener(this, RainStationWeekChartActivity.class)));
		
		List<String> keylist = new ArrayList<String>();
		for (int i = 0; i < keys.length; i++) {
			keylist.add(keys[i]);
		}	
		
		ListTableAdapter adapter = new ListTableAdapter(this,list,R.layout.rain_list_item,from,to,items,keylist);
		ListView lstRainStation = (ListView) findViewById(R.id.lstRainStation);
		lstRainStation.setAdapter(adapter);
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_SEARCH, 1, R.string.menu_search);
		menu.add(0, MENU_ONE, 2, R.string.menu_one);
		menu.add(0, MENU_THREE, 3, R.string.menu_three);
		menu.add(0, MENU_SIX, 4, R.string.menu_six);
		menu.add(0, MENU_DAY, 5, R.string.menu_day);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case MENU_SEARCH:	
				Intent intent = new Intent();	
				intent.setClass(getApplicationContext(), StationSearchActivity.class);
				startActivity(intent);
				return true;
			case MENU_ONE:
				shiduan = CommConstant.Rain.ONE_HOUR;
				initComponent();
				return true;
			case MENU_THREE:
				shiduan = CommConstant.Rain.THREE_HOUR;
				initComponent();
				return true;
			case MENU_SIX:	
				shiduan = CommConstant.Rain.SIX_HOUR;
				initComponent();
				return true;
			case MENU_DAY:	
				shiduan = CommConstant.Rain.DAY_HOUR;
				initComponent();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	protected void onDestroy() {     
        super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}

}